const bcrypt = require("bcryptjs/dist/bcrypt");
const db = require("../db");
const bscrypt = require("bcryptjs");
const config = require("../config");
const jwt = require("jsonwebtoken");
const { log } = require("async");

// 注册新用户
exports.reguser = (req, res) => {
  // 获取客户端提交到服务器的数据
  const userInfo = req.body;
  if (!userInfo.username || !userInfo.password) {
    return res.cc("用户名或密码不合法");
  }
  const sqlStr = "select * from ev_users where username=?";
  db.query(sqlStr, userInfo.username, (err, results) => {
    if (err) return res.cc(err);
    if (results.length > 0) {
      return res.cc("用户名被占用");
    }
    // 对密码进行加密
    userInfo.password = bscrypt.hashSync(userInfo.password, 10);
    //  插入用户数据
    const sql = "insert into ev_users set ?";
    db.query(
      sql,
      { username: userInfo.username, password: userInfo.password },
      (err, result) => {
        if (err) {
          return res.cc(err);
        }

        if (result.affectedRows !== 1) {
          return res.cc("注册用户失败，请稍后再试");
        }
        return res.cc("注册用户成功", 200);
      }
    );
  });
};
exports.login = (req, res) => {
  // 获取用户信息
  const userInfo = req.body;
  const sql = "select * from ev_users where username = ?";
  db.query(sql, userInfo.username, (err, results) => {
    if (err) return res.cc(err.message);
    if (results.length !== 1) return res.cc("当前用户不存在，请先注册用户!");
    // 判断密码是否正确
    const comparseRes = bcrypt.compareSync(
      userInfo.password,
      results[0].password
    );
    if (!comparseRes) return res.cc("登录失败");
    //  在服务器中生成token字符串
    const user = { ...results[0], password: "", user_pic: "" };
    const tokenStr = jwt.sign(user, config.jtwSecreKey, {
      expiresIn: config.expiresIn,
    });
    res.send({
      status: 200,
      message: "登录成功",
      data:{
        token:'Bearer '+ tokenStr
      }
    });
  });
};
